package com.guardchina.framework.util.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.guardchina.framework.util.gson.LocalDateSerializer;
import com.guardchina.framework.util.gson.LocalDateTimeSerializer;
import com.guardchina.framework.util.gson.LocalTimeSerializer;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 描述
 *
 * @author lwb
 * @since 2019/12/19
 */
public class GsonUtil {

    public static Gson createLocalDateTimeGson(String pattern){
        LocalDateTimeSerializer localDateTimeSerializer = new LocalDateTimeSerializer(pattern);

        return new GsonBuilder().registerTypeAdapter(LocalDateTime.class, localDateTimeSerializer).create();
    }

    public static Gson createLocalDateGson(String pattern){
        LocalDateSerializer localDateSerializer = new LocalDateSerializer(pattern);

        return new GsonBuilder().registerTypeAdapter(LocalDate.class, localDateSerializer).create();
    }

    public static Gson createLocalTimeGson(String pattern){
        LocalTimeSerializer localTimeSerializer = new LocalTimeSerializer(pattern);

        return new GsonBuilder().registerTypeAdapter(LocalTime.class, localTimeSerializer).create();
    }

    public static Gson createLocalDateTimeGson(String localDateTimePattern, String localDatePattern, String localTimePattern){
        GsonBuilder gsonBuilder = new GsonBuilder();
        if(StringUtils.isNotBlank(localDateTimePattern)){
            LocalDateTimeSerializer localDateTimeSerializer = new LocalDateTimeSerializer(localDateTimePattern);
            gsonBuilder.registerTypeAdapter(LocalDateTime.class, localDateTimeSerializer);
        }

        if(StringUtils.isNotBlank(localDatePattern)){
            LocalDateSerializer localDateSerializer = new LocalDateSerializer(localDatePattern);
            gsonBuilder.registerTypeAdapter(LocalDate.class, localDateSerializer);
        }

        if(StringUtils.isNotBlank(localTimePattern)){
            LocalTimeSerializer localTimeSerializer = new LocalTimeSerializer(localTimePattern);
            gsonBuilder.registerTypeAdapter(LocalTime.class, localTimeSerializer);
        }

        return gsonBuilder.create();
    }
}
